package com.old.model;

import com.aliyun.oos.demo.AliyunOSSClientUtil;
import com.aliyun.oss.OSSClient;
import com.google.gson.Gson;
import com.old.model.dbutil.Dbconn;
import com.old.people.DB;
import com.old.user.User_model;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.net.ssl.HttpsURLConnection;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.ConnectException;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;


public class Model {

    private PreparedStatement ps;
    private ResultSet rs;
    Dbconn s = new Dbconn();
    User_model user = new User_model();

    /**
     * 通过用户名邮箱进行登陆
     *
     * @param username
     * @param password
     * @return
     */
    public boolean checkUser(String username, String password) {
        user = this.queryByName(username);
        if (user != null) {
            return (username.equals(user.getName()) && password.equals(user
                    .getPassword()));
        } else
            return false;
    }

    /**
     * 是否存在用户
     *
     * @param name
     * @return
     */
    public User_model queryByName(String name) {
        User_model user = null;
        String sql = "select * from nsi_user where UserName = ? ";
        try {
            Connection conn = s.getConnection();
            ps = conn.prepareStatement(sql);
            ps.setString(1, name);
            rs = ps.executeQuery();
            if (rs.next()) {
                user = new User_model();
                user.setId(rs.getInt("Id"));
                user.setName(rs.getString("UserName"));
                user.setPassword(rs.getString("Password"));
                user.setUser_TureName(rs.getString("User_TureName"));
                user.setMember_sign(Integer.parseInt(rs.getString("Member_sign")));
                user.setUser_portrait(rs.getString("User_portrait"));

            }
            s.closeAll(conn, ps, rs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user;
    }

    /**
     * 通过用户名手机号进行登陆
     *
     * @param phone
     * @param password
     * @return
     */
    public boolean checkUserPhone(String phone, String password) {
        user = this.queryByPhone(phone);
        if (user != null) {
            return (phone.equals(user.getUser_phone()) && password.equals(user
                    .getPassword()));
        } else
            return false;
    }

    /**
     * 是否存在手机号
     *
     * @param phone
     * @return
     */
    public User_model queryByPhone(String phone) {
        User_model user = null;
        String sql = "select * from nsi_user where User_phone = ? order by Load_time";
        try {
            Connection conn = s.getConnection();
            ps = conn.prepareStatement(sql);
            ps.setString(1, phone);
            rs = ps.executeQuery();
            if (rs.next()) {
                user = new User_model();
                user.setName(rs.getString("UserName"));
                user.setUser_phone(rs.getString("User_phone"));
                user.setPassword(rs.getString("Password"));
                user.setUser_TureName(rs.getString("User_TureName"));
                user.setMember_sign(Integer.parseInt(rs.getString("Member_sign")));
            }
            s.closeAll(conn, ps, rs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user;
    }

    /**
     * 检查用户标志位是否未激活
     *
     * @param name
     * @return
     */
    public boolean queryByCode(String name) {
        User_model user = null;
        boolean checkCode = false;
        String sql = "select * from nsi_user where UserName = ? AND Member_sign > 0";
        try {
            Connection conn = s.getConnection();
            ps = conn.prepareStatement(sql);
            ps.setString(1, name);
            rs = ps.executeQuery();
            if (rs.next()) {
                checkCode = true;
            }
            s.closeAll(conn, ps, rs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("code验证：" + checkCode);
        return checkCode;
    }

    // 待修改 为ID查询 暂时用不到
//	查询用户等级标志位
    public int queryById(String name) {
        User_model user = null;
        int User_Member_sign = -2;
        String sql = "select * from nsi_user where UserName = ?";
        try {
            Connection conn = s.getConnection();
            ps = conn.prepareStatement(sql);
            ps.setString(1, name);
            rs = ps.executeQuery();
            if (rs.next()) {
                user = new User_model();
                user.setName(rs.getString("UserName"));
                user.setMember_sign(Integer.parseInt(rs.getString("Member_sign")));
            }
            s.closeAll(conn, ps, rs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        User_Member_sign = user.getMember_sign();
        System.out.println("Model 查询用户等级为：" + User_Member_sign);
        return User_Member_sign;
    }


    //	用户cookie校验
    public int UserVerify(String username, String member_sign, String UserVerifyCode) {
//		1、用户存不存在？
//		2、权限标记位是否正确？
//		3、校验和是否正确？
        User_model user = null;
        int CookieVerify = -3;
        String sql = "select * from nsi_user where UserName = '" + username + "'";
        int aa = DB.count(sql);
        if (aa >= 1) {
            try {
                Connection conn = s.getConnection();
                ps = conn.prepareStatement(sql);
                rs = ps.executeQuery();
                if (rs.next()) {
                    user = new User_model();
                    user.setName(rs.getString("UserName"));
                    user.setMember_sign(Integer.parseInt(rs.getString("Member_sign")));
                }
                s.closeAll(conn, ps, rs);
            } catch (Exception e) {
                e.printStackTrace();
            }
            String bb = String.valueOf(user.getMember_sign());

            if (member_sign.equals(bb)) {
                int cc = username.length() * Integer.parseInt(member_sign) + 987654;
                if (cc == Integer.parseInt(UserVerifyCode)) {
                    CookieVerify = 1;
                }
            } else {
                CookieVerify = -1;
            }

        } else {
            CookieVerify = -2;
        }
        System.out.println("Model 用户cookie校验为：" + CookieVerify);
        return CookieVerify;
    }

    //	判断邮箱是否存在
    public int UserExistence(String username) {
//		1、用户存不存在？
        User_model user = null;
        int CookieVerify = -3;
        String sql = "select * from nsi_user where UserName = '" + username + "'";
        int aa = DB.count(sql);
        if (aa >= 1) {
            CookieVerify = 1;
        } else {
            CookieVerify = -1;
        }
        System.out.println("Model 用户邮箱是否存在：" + CookieVerify);
        return CookieVerify;
    }


    //	文件上传通用组件
    public static int UpFileTool(String FileType, String UserMail, String User_TureName, HttpServletRequest request, int Id) throws ServletException, IOException {

//		上传文件，保存在哪里？什么格式？
        System.out.println("UpFileTool通用文件上传工具类:");
        // 上传配置
        final int MEMORY_THRESHOLD = 1024 * 1024 * 5;  // 5MB
        final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
        final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB
//	    	文件名：姓名+邮箱

        // 配置上传参数
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // 设置临时存储目录
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
        ServletFileUpload upload = new ServletFileUpload(factory);
        // 设置最大文件上传值、最大请求值 (包含文件和表单数据)、中文处理
        upload.setFileSizeMax(MAX_FILE_SIZE);
        upload.setSizeMax(MAX_REQUEST_SIZE);
        upload.setHeaderEncoding("UTF-8");
        // 弃用
        String uploadPath = "null";
        String filePath = "null";
        String sql = "";
        // 这个路径相对当前应用的目录
        //用户头像
        if (FileType.equals("UserPortrait")) {
            filePath = "C:" + File.separator + "upImage" + File.separator + "upUserImg" + File.separator + UserMail + User_TureName + ".png";
            uploadPath = "C:" + File.separator + "upImage" + File.separator + "upUserImg" + File.separator;
            sql = "UPDATE NSI_user SET User_portrait='/upImage/upUserImg/" + UserMail + User_TureName + ".png' where UserName='" + UserMail + "' ";

            //学校logo
        } else if (FileType.equals("SchoolLogo")) {
            filePath = "C:" + File.separator + "upImage" + File.separator + "upSchoolImg" + File.separator + Id + File.separator + Id + "-logo.png";
            uploadPath = "C:" + File.separator + "upImage" + File.separator + "upSchoolImg" + File.separator + Id + File.separator;
            sql = "UPDATE nsi_school_data SET School_logo='/upImage/upSchoolImg/" + Id + "/" + Id + "-logo.png' WHERE Id='" + Id + "' ";
            //学校展示
        } else if (FileType.equals("SchoolShow")) {
            filePath = "C:" + File.separator + "upImage" + File.separator + "upSchoolImg" + File.separator + Id + File.separator + Id + "-show.png";
            uploadPath = "C:" + File.separator + "upImage" + File.separator + "upSchoolImg" + File.separator + Id + File.separator;
            sql = "UPDATE nsi_school_data SET School_Show='/upImage/upSchoolImg/" + Id + "/" + Id + "-show.png' WHERE Id='" + Id + "' ";


            //机构logo
        } else if (FileType.equals("InstitutionLogo")) {
            filePath = "C:" + File.separator + "upImage" + File.separator + "upInstitutionImg" + File.separator + Id + File.separator + Id + "-logo.png";
            uploadPath = "C:" + File.separator + "upImage" + File.separator + "upInstitutionImg" + File.separator + Id + File.separator;
            sql = "UPDATE nsi_institution_data SET Institution_logo='/upImage/upInstitutionImg/" + Id + "/" + Id + "-logo.png' WHERE Id='" + Id + "' ;";
            //机构展示
        } else if (FileType.equals("InstitutionShow")) {
            filePath = "C:" + File.separator + "upImage" + File.separator + "upInstitutionImg" + File.separator + Id + File.separator + Id + "-show.png";
            uploadPath = "C:" + File.separator + "upImage" + File.separator + "upInstitutionImg" + File.separator + Id + File.separator;
            sql = "UPDATE nsi_institution_data SET Institution_show='/upImage/upInstitutionImg/" + Id + "/" + Id + "-show.png' WHERE Id='" + Id + "' ;";


            //项目logo
        } else if (FileType.equals("ProjectLogo")) {
            filePath = "C:" + File.separator + "upImage" + File.separator + "upProjectImg" + File.separator + Id + File.separator + Id + "-logo.png";
            uploadPath = "C:" + File.separator + "upImage" + File.separator + "upProjectImg" + File.separator + Id + File.separator;
            sql = "UPDATE nsi_project_data SET Subject_logo='/upImage/upProjectImg/" + Id + "/" + Id + "-logo.png' WHERE Id='" + Id + "' ;";

            //项目展示
        } else if (FileType.equals("ProjectShow")) {
            filePath = "C:" + File.separator + "upImage" + File.separator + "upProjectImg" + File.separator + Id + File.separator + Id + "-show.png";
            uploadPath = "C:" + File.separator + "upImage" + File.separator + "upProjectImg" + File.separator + Id + File.separator;
            sql = "UPDATE nsi_project_data SET Subject_Show='/upImage/upProjectImg/" + Id + "/" + Id + "-show.png' WHERE Id='" + Id + "' ;";
        }

//	        // 如果目录不存在则创建
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }

        int i = -2;
        try {
// 				解析请求的内容提取文件数据
//	        	忽略警告或错误信息
//	            @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(request);
            if (formItems != null && formItems.size() > 0) {
                // 迭代表单数据
                for (FileItem item : formItems) {
                    // 处理不在表单中的字段
                    if (!item.isFormField()) {
//	                    	获取上传文件名,FormatName为文件格式
                        String fileFormat = item.getName();
                        //FormatName带点；FormatName02不带点
                        //String FormatName = fileFormat.substring(fileFormat.lastIndexOf("."));
                        //String FormatName02 = fileFormat.substring(fileFormat.lastIndexOf(".")+1);

//	                        String filePath = uploadPath + UserMail+User_TureName+FormatName;
                        File storeFile = new File(filePath);
                        // 在控制台输出文件的上传路径
                        System.out.println("通用图片上传-模块：" + FileType + "-上传地址：" + filePath);
                        // 保存文件到硬盘
                        item.write(storeFile);
                        i = 1;
                    }
                }
                //传入sql,传入00不执行
                if (sql.length() > 5) {
                    DB.alter(sql);
                }
            }
        } catch (Exception ex) {
            System.err.println("文件上传模块-错误详情：" + ex.getMessage());
            i = -1;
        }
        return i;
    }

    //	富文本编辑器图片上传
    public static String TextEditor_upImg(HttpServletRequest request) throws ServletException, IOException {
//		上传文件，保存在哪里？什么格式？
        System.out.println("TextEditor_upImg通用图片上传工具类:");
        // 上传配置
        final int MEMORY_THRESHOLD = 1024 * 1024 * 5;  // 5MB
        final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
        final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB
        // 配置上传参数
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // 设置临时存储目录
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
        ServletFileUpload upload = new ServletFileUpload(factory);
        // 设置最大文件上传值、最大请求值 (包含文件和表单数据)、中文处理
        upload.setFileSizeMax(MAX_FILE_SIZE);
        upload.setSizeMax(MAX_REQUEST_SIZE);
        upload.setHeaderEncoding("UTF-8");
        // 弃用
        String uploadPath = "null";
        String filePath = "null";
        String sql = "";
        String FormatName = "";
//			当前时间
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String SubmitDate = formatter.format(currentTime);
        //课程介绍
        filePath = "C:" + File.separator + "upImage" + File.separator + "nsi-class" + File.separator + "course-detail" + File.separator + SubmitDate + File.separator + randomUtil();
        uploadPath = "C:" + File.separator + "upImage" + File.separator + "nsi-class" + File.separator + "course-detail" + File.separator + SubmitDate;
        sql = "";

//	        // 如果目录不存在则创建
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }

        int i = -2;
        try {
// 				解析请求的内容提取文件数据\忽略警告或错误信息
//	            @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(request);
            if (formItems != null && formItems.size() > 0) {
                // 迭代表单数据
                for (FileItem item : formItems) {
                    // 处理不在表单中的字段
                    if (!item.isFormField()) {
//	                    	获取上传文件名,FormatName为文件格式
                        String fileFormat = item.getName();
                        //FormatName带点；FormatName02不带点
                        FormatName = fileFormat.substring(fileFormat.lastIndexOf("."));
//							String FormatName02 = fileFormat.substring(fileFormat.lastIndexOf(".")+1);
                        File storeFile = new File(filePath + FormatName);
                        System.out.println("富文本编辑器图片上传-模块：上传地址：" + filePath + FormatName);
                        // 保存文件到硬盘
                        item.write(storeFile);
                        i = 1;
                    }
                }
                //传入sql,传入00不执行
                if (sql.length() > 5) {
                    DB.alter(sql);
                }
            }
        } catch (Exception ex) {
            System.err.println("文件上传模块-错误详情：" + ex.getMessage());
            i = -1;
        }
        String back = filePath + FormatName;
        back = back.substring(2, back.length());
        return back;
    }


    public static String OOSupImg(HttpServletRequest request) throws ServletException, IOException {
//		上传文件，保存在哪里？什么格式？
        System.out.println("TextEditor_upImg通用图片上传工具类:");
        // 上传配置
        final int MEMORY_THRESHOLD = 1024 * 1024 * 5;  // 5MB
        final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
        final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB
        // 配置上传参数
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // 设置临时存储目录
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
        ServletFileUpload upload = new ServletFileUpload(factory);
        // 设置最大文件上传值、最大请求值 (包含文件和表单数据)、中文处理
        upload.setFileSizeMax(MAX_FILE_SIZE);
        upload.setSizeMax(MAX_REQUEST_SIZE);
        upload.setHeaderEncoding("UTF-8");
        // 弃用
        String FormatName = "";
//			当前时间
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String SubmitDate = formatter.format(currentTime);
        //课程介绍
//	    	文件名随机数，文件路径，文件全路径；

        String randomUtil = randomUtil();
        String uploadPath = "C:" + File.separator + "upImage" + File.separator + "nsi-class" + File.separator + "course-detail" + File.separator + SubmitDate;
        String filePath = uploadPath + File.separator + randomUtil;
        String sql = "";

//	        // 如果目录不存在则创建
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
        String back = "orginNull";
        try {
// 				解析请求的内容提取文件数据\忽略警告或错误信息
//	            @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(request);
            if (formItems != null && formItems.size() > 0) {
                // 迭代表单数据
                for (FileItem item : formItems) {
                    // 处理不在表单中的字段
                    if (!item.isFormField()) {
//	                    	获取上传文件名,FormatName为文件格式
                        String fileFormat = item.getName();
                        //FormatName带点；FormatName02不带点
                        FormatName = fileFormat.substring(fileFormat.lastIndexOf("."));
//							String FormatName02 = fileFormat.substring(fileFormat.lastIndexOf(".")+1);
                        File storeFile = new File(filePath + FormatName);
                        System.out.println("富文本编辑器图片上传-模块：上传地址：" + filePath + FormatName);
                        // 保存文件到硬盘
                        item.write(storeFile);
                        // 保存文件到阿里云oos
                        //初始化OSSClient
                        OSSClient ossClient = AliyunOSSClientUtil.getOSSClient();
                        String md5key = AliyunOSSClientUtil.uploadObject2OSS(ossClient, storeFile, "nsi", "test/");
//	                        item.write(storeFile);
                        back = randomUtil + FormatName;
                        System.out.println("back:" + back);
                    }
                }
            }
        } catch (Exception ex) {
            System.err.println("阿里云文件上传模块-错误详情：" + ex.getMessage());
            back = "error!!";
        }
        return back;
    }


    //	微信扫码依赖方法
//	未完成
    public static String WechatHttpRequest(String requestUrl, String requestMethod, String outputStr) {
        String WechatId = null;

        StringBuffer buffer = new StringBuffer();
        try {

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod(requestMethod);

            if ("GET".equalsIgnoreCase(requestMethod))
                httpUrlConn.connect();

            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式，防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();

            Gson gson = new Gson();
            String WechatJson = gson.toJson(buffer.toString());

            System.out.println(WechatJson);
            System.out.println("字符截取序号" + WechatJson.indexOf("openid") + " 到 " + WechatJson.indexOf("scope"));

            WechatId = WechatJson.substring(WechatJson.indexOf("openid") + 11, WechatJson.indexOf("scope") - 5);

//            Gson gson02 = new Gson();
            System.out.println("-------------------------------------------------");
            System.out.println(WechatJson);
            System.out.println("-------------------------------------------------------");
            System.out.println("i am WechatId:" + WechatId);

        } catch (ConnectException ce) {
            System.out.println(ce);
        } catch (Exception e) {
            System.out.println(e);
        }
        return WechatId;
    }

    //	微信分享依赖方法-获取ticket
//	测试中
    public static String WechatShareGetTicket(String requestUrl, String requestMethod, String outputStr) {
//		System.out.println("------------------第2步：获取ticket 开始执行----------------------");
        String WechatId = null;
        StringBuffer buffer = new StringBuffer();
        try {

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod(requestMethod);

            if ("GET".equalsIgnoreCase(requestMethod))
                httpUrlConn.connect();

            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式，防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();

            Gson gson = new Gson();
            String WechatJson = gson.toJson(buffer.toString());

//            System.out.println("第2步：获取ticket 页面请求返回值："+WechatJson);
//            System.out.println("字符截取序号"+WechatJson.indexOf("ticket")+" 到 "+WechatJson.indexOf("expires_in"));
            WechatId = WechatJson.substring(WechatJson.indexOf("ticket") + 11, WechatJson.indexOf("expires_in") - 5);

        } catch (ConnectException ce) {
            System.out.println(ce);
        } catch (Exception e) {
            System.out.println(e);
        }
        return WechatId;
    }


    //	微信分享依赖方法-获取access_token
//	测试中
    public static String WechatShareAccess_token(String requestUrl, String requestMethod, String outputStr) {
        String WechatId = null;
        StringBuffer buffer = new StringBuffer();
//        System.out.println("------------------第1步：获取access_token 开始执行----------------------");
        try {

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod(requestMethod);

            if ("GET".equalsIgnoreCase(requestMethod))
                httpUrlConn.connect();

            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式，防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();

            Gson gson = new Gson();
            String WechatJson = gson.toJson(buffer.toString());

//            System.out.println("字符截取序号"+WechatJson.indexOf("access_token")+" 到 "+WechatJson.indexOf("expires_in"));
            WechatId = WechatJson.substring(WechatJson.indexOf("access_token") + 17, WechatJson.indexOf("expires_in") - 5);


        } catch (ConnectException ce) {
            System.out.println(ce);
        } catch (Exception e) {
            System.out.println(e);
        }
        return WechatId;
    }

    /**
     * 公共调用方法
     *
     * @param sign    功能API名字
     * @param index01 执行操作
     * @param index02 时间(yyyy-MM-dd)
     * @param index03 执行操作
     * @param index04 真实姓名
     * @param index05
     * @return 无参
     */
    public void commonLog(String sign, String index01, String index02, String index03, String index04, String index05) {
        Connection conn = null;
        String sql = "insert into nsi_log (sign,index01,index02,index03,index04,index05)VALUES(?,?,?,?,?,?)";
        try {
            conn = s.getConnection();
            ps = conn.prepareStatement(sql);
            ps.setString(1, sign);
            ps.setString(2, index01);
            ps.setString(3, index02);
            ps.setString(4, index03);
            ps.setString(5, index04);
            ps.setString(6, index05);
            int rows = ps.executeUpdate();
            if (rows > 0) {
//				System.out.println("commonLog插入成功...");
            } else {
                System.out.println("commonLog插入失败...");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //当前时间
    public String submitTime() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String subTime = sdf.format(date);
        return subTime;
    }

    //	8位随机数
    public static String randomUtil() {
        Random r = new Random();
        String code = "";
        for (int i = 0; i < 8; ++i) {
            int temp = r.nextInt(52);
            char x = (char) (temp < 26 ? temp + 97 : (temp % 26) + 65);
            code += x;
        }
        return code;
    }
}
